import functools
class Solution(object):
    def judgePoint24(self, cards):
        tp = []
        used = [0] * 4
        out = []

        def dfs(i):
            if i == 4:
                tp.append(tuple(out))
            else:
                for j in range(4):
                    if used[j] == 0:
                        out.append(cards[j])
                        used[j] = 1
                        dfs(i + 1)
                        out.pop()
                        used[j] = 0
        dfs(0)
        @functools.cache
        def search(i, j, arr):
            if i == j:
                return {arr[i]}
            else:
                ans = set()
                for k in range(i, j):
                    ans1 = search(i, k, arr)
                    ans2 = search(k + 1, j, arr)
                    for v1 in ans1:
                        for v2 in ans2:
                            ans.update({v1 + v2, v1 - v2, v1 * v2})
                            if v2 != 0:
                                ans.add(v1 / v2)
                return ans

        for arr in tp:
            t = search(0, 3, arr)
            for val in t:
                if abs(val - 24) <= 0.00001:
                    return True
        return False



data = Solution()
cards = [3,3,8,8]
print(data.judgePoint24(cards))
